<!--
 * @Author       : Hejh(3010733382@qq.com)
 * @Version      : V1.0
 * @Date         : 2024-01-29 20:04:48
 * @Description  : 用户激活科目管理
-->
<template>
  <div
    class="bg-lightColor userActiveExam-con p-3 rounded relative"
    v-if="editModel === 'view'"
  >
    <n-grid x-gap="12" :cols="1" class="mb-2" v-permission="['admin']">
      <n-gi>
        <n-button
          type="primary"
          size="small"
          class="!text-[13px]"
          @click="handleToAdd"
        >
          <SvgIcon
            icon="zengjiatianjiajiahao"
            color="#badeff"
            class="mr-1"
          ></SvgIcon>
          新增
        </n-button>
      </n-gi>
    </n-grid>

    <n-flex align="center" class="mb-2">
      <UserSelect
        class="!w-[200px]"
        :multiple="false"
        @change-value="(value: any) => (queryInfo.userId = value)"
      ></UserSelect>

      <ExamSelect
        class="!w-[200px]"
        :multiple="false"
        @change-value="(value: any) => (queryInfo.examId = value)"
      ></ExamSelect>

      <n-button type="primary" @click="loadUserActiveExams" size="small">
        查询
      </n-button>
    </n-flex>

    <wp-data-table
      :pages="pageResultInfo.pages"
      :total="pageResultInfo.total"
      v-loading="loading"
      :data="data"
      :checked-row-keys="checkedRowKeys"
      :columns="columns"
      @page-change="handlePageChange"
      @select-change="handleSelectChange"
      @order-change="handleOrderChange"
    >
    </wp-data-table>
  </div>
  <create-and-update-userActiveExam
    :is-modify="editModel === 'update'"
    :userActiveExam-res="curUserActiveExam"
    @change-userActiveExam="handleAddAndUpdateUserActiveExam"
    v-else
    @back-view="editModel = 'view'"
  ></create-and-update-userActiveExam>
</template>

<script setup lang="ts">
import { useMessage, NButton, useDialog } from 'naive-ui'
import type { DataTableColumn, DataTableColumns } from 'naive-ui'
import useUserStore from '@/stores/modules/user'
import {
  createUserActiveExam,
  delUserActiveExam,
  getUserActiveExamByPage,
  sortUserActiveExam,
  updateUserActiveExam
} from '@/api/userActiveExam'
import type {
  UserActiveExamCreateReq,
  UserActiveExamReq,
  UserActiveExamRes,
  UserActiveExamRowData,
  UserActiveExamUpdateReq
} from '@/types/userActiveExam'
import { load } from '@/utils/loading'
import { renderSort } from '@/utils/commonBusiness'
import SvgIcon from '@/components/SvgIcon/index.vue'
import WpDataTable from '@/components/WpDataTable/index.vue'
import PicValidCode from '@/components/PicValidCode/index.vue'
import CreateAndUpdateUserActiveExam from './components/CreateAndUpdateUserActiveExam.vue'
import { arrayToTree, formatTime } from '@/utils'

const userStore = useUserStore()
const message = useMessage()
const dialog = useDialog()

// const showDialog = ref(true)

const data = ref<UserActiveExamRowData[]>([])
const pageInfo = reactive({
  page: 1,
  pageSize: 50
})

const queryInfo = reactive({
  userId: '',
  examId: ''
})
const loading = ref(false)

const pageResultInfo = reactive({
  pages: 0,
  total: 0
})

const createColumns = (): DataTableColumns<UserActiveExamRowData> => {
  const selectColumn: DataTableColumn<UserActiveExamRowData> = {
    type: 'selection',
    minWidth: 30,
    width: 30
  }

  const actionColumns: DataTableColumns<UserActiveExamRowData> = [
    {
      title: '操作',
      key: 'actions',
      minWidth: 200,
      width: 200,
      render(row) {
        return h('div', [
          // h(
          //   NButton,
          //   {
          //     text: true,
          //     type: 'primary',
          //     size: 'small',
          //     class: 'text-[13px]',
          //     onClick: () => handleToUpdate(row)
          //   },
          //   { default: () => '编辑' }
          // ),
          h(
            NButton,
            {
              text: true,
              type: 'primary',
              size: 'small',
              class: 'ml-2 text-[13px]',
              onClick: () => handleToDel(row)
            },
            { default: () => '取消激活' }
          )
        ])
      }
    }
  ]

  const staticColumns: DataTableColumns<UserActiveExamRowData> = [
    {
      title: '用户名称',
      key: 'userId',
      minWidth: 120,
      width: 120,
      render: (row) => {
        return renderSort(() => `${row.User.username}`)
      }
    },
    {
      title: '科目名称',
      key: 'examId',
      minWidth: 120,
      width: 120,
      render: (row) => {
        return row.Exam ? row.Exam.name : '无'
      }
    },
    {
      title: '所用激活码',
      key: 'activeCode',
      minWidth: 120,
      width: 120
    },
    {
      title: '激活时间',
      key: 'createTime',
      minWidth: 120,
      width: 120,
      render: (row) => {
        return formatTime(row.createTime)
      }
    }
  ]

  // 判断用户是否具有编辑权限

  if (
    userStore.permissions?.some((item: any) => {
      return item === 'admin'
    })
  ) {
    staticColumns.unshift(selectColumn)
    staticColumns.push(...actionColumns)
  }

  return staticColumns
}

const checkedRowKeys = ref<string[]>([])

const columns = createColumns()

// 获取用户激活科目列表
const loadUserActiveExams = () => {
  loading.value = true
  let param: UserActiveExamReq = {
    ...pageInfo
  }
  if (queryInfo.userId) {
    param.userId = queryInfo.userId
  }
  if (queryInfo.examId) {
    param.examId = queryInfo.examId
  }

  getUserActiveExamByPage(param)
    .then((res) => {
      console.log(res)
      data.value = res.data.items
      pageResultInfo.pages = res.data.pages
      pageResultInfo.total = res.data.total
      // data.value = arrayToTree(res.data.items, 'pid', '-1')
    })
    .catch(console.error)
    .finally(() => {
      loading.value = false
    })
}

onMounted(() => {
  loadUserActiveExams()
})

const handlePageChange = (page?: number, pageSize?: number) => {
  page && (pageInfo.page = page)
  pageSize && (pageInfo.pageSize = pageSize)
  loadUserActiveExams()
}

const handleSelectChange = (rows: string[]) => {
  checkedRowKeys.value = rows.map((item) => item)
}

// 去添加用户激活科目
const handleToAdd = () => {
  editModel.value = 'create'
}

const curUserActiveExam = ref<UserActiveExamRes>()
// 去编辑用户激活科目
const handleToUpdate = (row: UserActiveExamRowData) => {
  curUserActiveExam.value = row
  editModel.value = 'update'
}

// 去删除用户激活科目
const handleToDel = (row: UserActiveExamRowData) => {
  let dialogObj = dialog.warning({
    title: '你确定要删除这些用户激活科目吗？',
    class: '!w-[768px]',
    content: () =>
      h(
        PicValidCode,
        {
          showCloseIcon: false,
          class: '!w-full',
          onOnFinish: (picCode: string) => {
            load.show()
            delUserActiveExam([row.id], picCode)
              .then(() => {
                message.success('删除用户激活科目成功')
                afterOpt()
                dialogObj.destroy()
              })
              .catch(console.error)
              .finally(() => {
                load.hide()
              })
          }
        },
        []
      )
  })
}

// ================================= 用户激活科目新增和更新逻辑===============================================
const editModel = ref<'create' | 'update' | 'view'>('view')

const handleAddUserActiveExam = (data: UserActiveExamCreateReq) => {
  load.show()
  createUserActiveExam(data)
    .then(() => {
      message.success('添加用户激活科目成功')
      afterOpt()
    })
    .catch(console.error)
    .finally(() => {
      load.hide()
    })
}

const handleUpdateUserActiveExam = (data: UserActiveExamUpdateReq) => {
  load.show()
  updateUserActiveExam(data)
    .then(() => {
      message.success('更新用户激活科目成功')
      afterOpt()
    })
    .catch(console.error)
    .finally(() => {
      load.hide()
    })
}

const handleAddAndUpdateUserActiveExam = (
  type: number,
  data: UserActiveExamCreateReq | UserActiveExamUpdateReq
) => {
  if (type === 1) {
    handleUpdateUserActiveExam(data as UserActiveExamUpdateReq)
  } else {
    handleAddUserActiveExam(data as UserActiveExamCreateReq)
  }
}

const handleOrderChange = (newIndex: number, oldIndex: number) => {
  // 当前的顺序
  const ids = data.value.map((item) => item.id)
  const res = ids.splice(oldIndex, 1)
  ids.splice(newIndex, 0, ...res)
  sortUserActiveExam(ids)
    .then(() => {
      afterOpt()
    })
    .catch(console.error)
}

const afterOpt = () => {
  loadUserActiveExams()
  editModel.value = 'view'
}
</script>

<style scoped lang="scss">
.userActiveExam-con {
  font-size: 13px;

  :deep(.n-data-table-tbody .n-data-table-tr:hover .n-data-table-td) {
    background-color: #e5f3ff;

    .move {
      opacity: 0.85;
    }
  }

  :deep(.my-handle) {
    height: 28px;
    line-height: 28px;
    // height: calc(100% + 16px);
    position: relative;
    .move {
      transition: all 0.3s var(--n-bezier);
      opacity: 0;
      display: flex;
      justify-content: center;
      align-items: center;
      background-color: #d1ecfa;
      color: $primaryColor;
      position: absolute !important;
      left: -8px;
      top: -8px;
      bottom: -8px;
      width: 40px;
      // right: 0;
      cursor: move;
    }
  }
}
</style>
